import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from '../user/user.entity';
import { Permission } from './permission.entity';

@Injectable()
export class PermissionService {
  constructor(
    @InjectRepository(Permission)
    private permissionRepository: Repository<Permission>,
  ) { }

  async findAll(robotId?: number): Promise<Permission[]> {
    const where = robotId ? { robotId } : {};
    return this.permissionRepository.find({ where });
  }

  async findOne(id: number): Promise<Permission> {
    return this.permissionRepository.findOne({ where: { id } });
  }

  async create(createPermissionDto: any): Promise<Permission> {
    return this.permissionRepository.save(createPermissionDto);
  }

  async remove(id: number): Promise<void> {
    await this.permissionRepository.delete(id);
  }

  getPermission(userInfo, permissionList, robotInfo) {
    const permissionInfo: any = permissionList.find(e => e.robotId === robotInfo.id && e.userId === userInfo.id);

    // 1. 超级管理员：所有机器人全部设置为管理员
    // 2. 公共机器人：有当前用户如果是admin则设为admin，否则全部设为readonly
    // 3. 私有机器人：根据当前用户权限设置，没有则无权限

    let role = '';
    console.log('我的角色是', userInfo.isSuperAdmin);
    // 使用isSuperAdmin替代旧的role字段
    if (userInfo.isSuperAdmin) {
      role = 'admin';
      return role;
    }

    if (robotInfo.status === 'public') {
      role = !permissionInfo || permissionInfo.role !== 'admin' ? 'readonly' : 'admin';
      return role;
    }

    if (!permissionInfo) {
      role = 'none';
      return role;
    }

    role = permissionInfo.role;

    return role;
  }
} 